JSX (JavaScript XML) is a syntax extension used in React that allows developers to write HTML-like markup inside JavaScript code. Following JSX best practices makes React applications easier to read, maintain, debug, reuse, and scale.
JSX best practices are recommended coding techniques that help developers write clean, consistent, reusable, and error-free JSX code in React applications.
They include using meaningful component names, writing readable markup, keeping components small, using correct JSX attributes, handling lists with unique keys, and avoiding unnecessary complexity.
Example: Poor JSX vs. Better JSX
Poor JSX:
function App(){return <div><h1>welcome</h1><p>learn react</p><button>click</button></div>;}
Better JSX:
function App() {
return (
<div>
<h1>Welcome to React</h1>
<p>Learn React step by step.</p>
<button>Get Started</button>
</div>
);
}
The second example is easier to understand because the code is properly formatted and the content is meaningful.
2. Use Proper Indentation and Formatting
Always format JSX with consistent indentation and line breaks. Readable code makes it easier to identify nesting errors and understand the UI structure.
Example
function Profile() {
return (
<section className="profile">
<h2>User Profile</h2>
<p>Welcome to your profile.</p>
</section>
);
}
Best practices
Use consistent indentation throughout the project.
Place nested elements on separate lines when it improves readability.
Use parentheses around multiline JSX returned by a function.
Avoid putting an entire component on one long line.
Use a consistent formatter such as Prettier when available.
3. Use Meaningful Component Names
React component names should describe their purpose. Component names must begin with an uppercase letter so React can distinguish custom components from built-in HTML elements.
Incorrect
function usercard() {
return <div>User Information</div>;
}
Correct
function UserCard() {
return (
<div>
User Information
</div>
);
}
Common naming conventions
Item
Recommended style
Example
React component
PascalCase
UserCard
JavaScript variable
camelCase
userName
Function
camelCase
handleClick
Constant
UPPER_SNAKE_CASE when appropriate
MAX_ITEMS
CSS class
Consistent project convention
user-card
4. Use One Parent Element or a Fragment
A component must return one JSX expression. When you need multiple sibling elements, wrap them in a parent element or use a React Fragment.
Using a parent element
function Welcome() {
return (
<div>
<h1>Hello!</h1>
<p>Welcome to React.</p>
</div>
);
}
Using a Fragment
function Welcome() {
return (
<>
<h1>Hello!</h1>
<p>Welcome to React.</p>
</>
);
}
A Fragment groups elements without adding an extra DOM element. Prefer it when an additional wrapper is not needed for layout, styling, or semantics.
5. Use Correct JSX Attributes
JSX follows JavaScript-oriented naming conventions for many attributes. Some familiar HTML attributes have different names in JSX.
Best practice: Treat props as read-only. If a component needs to change information over time, use state or request an update through a callback provided by its parent.
10. Use Stable, Unique Keys When Rendering Lists
When you use map() to render multiple JSX elements, assign each sibling element a stable key. React uses keys to identify items as lists change.
function Notification({ messageCount }) {
return (
<div>
{messageCount > 0 && (
<p>You have new messages.</p>
)}
</div>
);
}
Best practices
Use ternary expressions for simple either-or decisions.
Use && when content should appear only when a condition is true.
Use an if statement before the return when the logic is more complex.
Avoid deeply nested ternary expressions.
Be careful with numeric conditions: {messageCount && ...} may display 0 when the count is zero. Prefer {messageCount > 0 && ...}.
12. Use Semantic HTML Elements
Choose HTML elements according to their meaning and purpose instead of using generic div elements for everything. Semantic HTML improves accessibility, maintainability, and document structure.
In JSX, event handlers use camelCase names such as onClick and onChange. Pass a function to the event handler rather than calling it immediately during rendering.
Incorrect
<button onClick={handleClick()}>Click Me</button>
This calls handleClick while rendering, rather than waiting for a click, unless the function is intentionally designed to return an event handler.
Correct
function ActionButton() {
function handleClick() {
alert("Button clicked!");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
You can also pass an inline arrow function when you need to provide arguments:
15. Keep Components Pure and Avoid Side Effects During Rendering
A component should calculate its JSX from its props, state, and other inputs without unexpectedly changing external values during rendering. Rendering may happen more than once, so side effects should not be performed directly in the component body.
Incorrect
let totalVisitors = 0;
function VisitorCounter() {
totalVisitors += 1;
return <p>Visitors: {totalVisitors}</p>;
}
Better
function VisitorCounter({ totalVisitors }) {
return <p>Visitors: {totalVisitors}</p>;
}
Pass values through props or manage changing data with React state. Use event handlers for user-triggered actions and effects for synchronization with external systems when appropriate.
16. Do Not Mutate Props or State Directly
Props and state should be treated as immutable values. Create a new array or object when updating state instead of modifying the existing value.
Incorrect state update
items.push("New Item");
setItems(items);
Correct state update
setItems(previousItems => [
...previousItems,
"New Item"
]);
This example assumes items is state managed by a setter named setItems. Creating a new array allows React to detect the updated state correctly.
17. Use Consistent Styling Approaches
Choose a styling approach that fits the project and apply it consistently. JSX supports the className attribute for CSS classes and the style prop for inline style objects.
function Notice() {
const noticeStyle = {
color: "darkgreen",
backgroundColor: "lightyellow",
padding: "12px"
};
return (
<p style={noticeStyle}>
Your changes have been saved.
</p>
);
}
Best practice: Prefer CSS classes for reusable styling. Inline styles are useful for simple, dynamic values, but they are JavaScript objects and their property names use camelCase.
18. Avoid Unnecessary Nesting and Wrapper Elements
Excessive nesting makes JSX harder to read and maintain. Use the simplest structure that accurately represents the interface.
Elements with children should have matching opening and closing tags:
<button type="button">
Learn More
</button>
20. Avoid Unsafe HTML Injection
React escapes ordinary text values rendered in JSX. Avoid using dangerouslySetInnerHTML unless you have a specific need to insert HTML markup and have properly sanitized the content.
Recommended for ordinary text
function Message({ text }) {
return <p>{text}</p>;
}
When HTML is inserted directly, untrusted content can create cross-site scripting (XSS) risks. If rich HTML is required, sanitize it with a trusted sanitizer and carefully control the source.
21. Use Tools to Maintain JSX Quality
Development tools help detect syntax mistakes, inconsistent formatting, accessibility issues, and common React errors.
ESLint: Identifies code-quality issues and common mistakes.
React ESLint rules: Help detect React-specific problems, including hook-rule violations when configured.
Prettier: Automatically formats JSX and JavaScript consistently.
Browser developer tools: Help inspect errors, warnings, and UI behavior.
React Developer Tools: Helps inspect the component tree, props, and state.
Automated tests: Help verify component behavior and user interactions.
22. Complete Practical Example: Applying JSX Best Practices
This example combines readable formatting, reusable components, props, stable keys, semantic HTML, and accessible controls.
The component structure is easy to extend and maintain.
23. Common JSX Mistakes and Their Solutions
Mistake
Correct approach
Using class in JSX
Use className.
Using lowercase custom component names
Use PascalCase, such as UserCard.
Returning sibling elements without a wrapper
Use a parent element or Fragment.
Rendering mapped elements without keys
Provide stable keys unique among siblings.
Writing complex logic inside markup
Move logic into variables or helper functions.
Calling an event handler during rendering
Pass the function, such as onClick={handleClick}.
Using an incorrect HTML label attribute
Use htmlFor in JSX.
Mutating state directly
Create a new array or object and update state with its setter.
Using a number directly as a conditional AND check
Use a boolean condition, such as count > 0.
Using unsafe HTML injection for ordinary text
Render text normally inside JSX.
24. JSX Best Practices Checklist
Use consistent indentation and formatting.
Use meaningful component names in PascalCase.
Use one parent element or a Fragment for sibling elements.
Use correct JSX attributes, such as className and htmlFor.
Use curly braces for JavaScript expressions.
Keep JSX expressions simple and readable.
Split large interfaces into reusable components.
Pass data through props and treat props as read-only.
Provide stable keys when rendering lists.
Keep conditional rendering easy to understand.
Use semantic HTML and accessible form controls.
Pass event-handler functions correctly.
Avoid side effects during rendering.
Do not mutate props or state directly.
Use consistent styling conventions.
Avoid unnecessary wrappers and deep nesting.
Use self-closing syntax for elements without children.
Avoid unsafe HTML injection.
Use linting, formatting, and testing tools.
25. Interview Questions and Answers
Q1. What are JSX best practices?
Answer: JSX best practices are coding guidelines that help developers create readable, maintainable, accessible, reusable, and reliable React interfaces.
Q2. Why should component names start with an uppercase letter?
Answer: React uses uppercase names to identify custom components. Lowercase names are interpreted as built-in HTML tags.
Q3. Why do we use className instead of class?
Answer: JSX uses the JavaScript-oriented attribute name className to assign CSS classes.
Q4. Why are keys important in React lists?
Answer: Keys help React identify list items across updates, insertions, deletions, and reordering.
Q5. What is the benefit of using React Fragments?
Answer: Fragments group multiple JSX elements without adding an unnecessary DOM wrapper.
Q6. Why should components be small and reusable?
Answer: Smaller components are easier to understand, test, debug, reuse, and maintain.
Q7. What is the difference between props and state?
Answer: Props are inputs passed to a component, usually by its parent. State is data managed by a component or its state-management logic that can change over time.
Q8. Why should state not be mutated directly?
Answer: Direct mutation can prevent React from detecting updates correctly and can lead to unpredictable UI behavior. Use state setters and create updated values instead.
Q9. Why is semantic HTML important in JSX?
Answer: Semantic HTML communicates the meaning of content and improves accessibility and maintainability.
Q10. How can developers maintain consistent JSX formatting?
Answer: They can use a consistent style guide and automatic formatting tools such as Prettier, together with ESLint for code-quality checks.
26. Conclusion
Following JSX best practices helps developers build React applications that are readable, accessible, reusable, and easier to maintain. Focus on clean formatting, meaningful components, simple expressions, stable list keys, correct attributes, semantic HTML, safe event handling, and immutable state updates.